<template>
  <el-card>
    <div class="VIALL">
      <div class="VILeft">
        <el-form :model="VIDrug" ref="VIDrug" @submit.prevent>
          <el-input
            v-model="VIDrug.dname"
            placeholder="请输入药品名称"
            @change="SearchDrug"
          >
            <template #append>
              <el-icon style="cursor: pointer" @click="SearchDrug">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form>
        <el-table
          :data="VIDrugLists"
          border
          id="eltable"
          height="65vh"
          :header-cell-style="{ 'text-align': 'center', 'font-size': '14px' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="dname" show-overflow-tooltip label="名称" />
          <el-table-column prop="dnorm" show-overflow-tooltip label="规格" />
          <el-table-column prop="did" label="操作">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="primary"
                @click="Check(scope.row.did)"
                >确认</el-button
              >
            </template>
          </el-table-column>
          <template v-slot:empty>
            <span style="color: #969799">未查询到药品信息</span>
          </template>
        </el-table>
      </div>
      <!-- 开处方 -->
      <el-dialog
        v-model="CheckDialogVisable"
        title="处方"
        width="400"
        align-center
      >
        <el-form :model="CDVdrug" ref="CDVdrug" :rules="rules">
          <el-form-item label="名称" prop="cdvname">
            <el-input v-model="CDVdrug.cdvname" disabled />
          </el-form-item>
          <el-form-item label="规格" prop="cdvnorm">
            <el-input v-model="CDVdrug.cdvnorm" disabled />
          </el-form-item>
          <el-form-item label="数量" prop="cdvnum">
            <el-input v-model="CDVdrug.cdvnum" />
          </el-form-item>
          <el-form-item label="使用" prop="cdvusing">
            <el-radio-group v-model="CDVdrug.cdvusing">
              <el-radio label="内服" border>内服</el-radio>
              <el-radio label="外用" border>外用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用法" prop="cdvuse">
            <el-input v-model="CDVdrug.cdvuse" placeholder="次/每日" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="Closed">关闭</el-button>
            <el-button type="primary" @click="Confirmed"> 生成处方 </el-button>
          </div>
        </template>
      </el-dialog>
      <div class="VIContent">
        <div class="VICHeader">
          <el-button
            type="large"
            @click="SavePrescription()"
            style="width: 100px; margin-left: 5px; margin-right: 5px"
            >保存处方</el-button
          >
          <el-button
            type="large"
            @click="AddPrescription()"
            style="width: 100px; margin-left: 5px"
            >添加处方</el-button
          >
          <el-button
            type="large"
            @click="SaveEdit()"
            style="width: 100px; margin-left: 5px"
            >保存修改</el-button
          >
          <el-button
            type="large"
            @click="EditPrescription()"
            style="width: 100px; margin-left: 5px"
            >修改处方</el-button
          >
        </div>
        <div class="VICContent">
          <h1>辛集市乡村卫生室处方</h1>
          <el-form :model="ViCaseHistory" ref="ViCaseHistory" :rules="rules">
            <el-row :gutter="24">
              <el-form-item label="姓名:" prop="cname" class="ViLabel">
                <el-input v-model="ViCaseHistory.cname" style="width: 160px" />
              </el-form-item>
              <el-form-item label="性别:" prop="sex" class="ViLabel">
                <el-select
                  v-model="ViCaseHistory.sex"
                  placeholder="性别"
                  style="width: 100px"
                >
                  <el-option label="男" value="1" />
                  <el-option label="女" value="0" />
                </el-select>
              </el-form-item>
              <el-form-item label="年龄:" prop="age" class="ViLabel">
                <el-input v-model="ViCaseHistory.age" style="width: 120px" />
              </el-form-item>
              <el-form-item label="体重:" prop="weight" class="ViLabel">
                <el-input
                  v-model="ViCaseHistory.weight"
                  placeholder="Kg"
                  style="width: 160px"
                />
              </el-form-item>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="电话:" prop="telephone" class="ViLabel">
                <el-input
                  v-model="ViCaseHistory.telephone"
                  style="width: 160px"
                />
              </el-form-item>
              <el-form-item label="地址:" prop="address" class="ViLabel">
                <el-input
                  v-model="ViCaseHistory.address"
                  style="width: 551px"
                />
              </el-form-item>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="过敏及特殊病史:" prop="chistory" id="exra">
                <el-input
                  v-model="ViCaseHistory.chistory"
                  style="width: 726px"
                />
              </el-form-item>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="诊断:" prop="vresult" class="ViLabel">
                <el-input
                  v-model="ViCaseHistory.vresult"
                  style="width: 795px"
                />
              </el-form-item>
            </el-row>
            <el-row :gutter="24">
              <h2 style="font-size: 30px; margin-left: 40px">Rp</h2>
            </el-row>
            <el-row :gutter="24">
              <el-form-item label="处置:" prop="vmethod" class="ViLabel">
                <el-input
                  v-model="ViCaseHistory.vmethod"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  style="width: 795px"
                  type="textarea"
                  :disabled="Flag"
                />
              </el-form-item>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="VIRight">
        <el-form :model="VIPerI" ref="VIPerI" @submit.prevent>
          <el-input
            v-model="VIPerI.name"
            placeholder="输入患者姓名或健康档案号"
            @change="SearchPerI"
          >
            <template #append>
              <el-icon style="cursor: pointer" @click="SearchPerI">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form>
        <el-table
          :data="VIPerRrcords"
          border
          id="eltable"
          height="65vh"
          :header-cell-style="{ 'text-align': 'center', 'font-size': '14px' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="rid" label="操作">
            <template #default="scope">
              <el-button
                size="small"
                @click="Selection(scope.row.rid)"
                link
                type="primary"
                >确认</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="idcard" show-overflow-tooltip label="卡号" />
          <template v-slot:empty>
            <span style="color: #969799">未查询到患者信息</span>
          </template>
        </el-table>
        <div class="VIadd">
          <el-button type="large" @click="temporaryIdCard()">新增</el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { ref } from "vue";
import {
  queryVIPerRrcord,
  queryVIDrug,
  AddCH,
  delData,
  DrugUsingComputed,
  SaveEditPrescription,
} from "@/api/visitInfo";
import { QueryPatientByIdCard } from "@/api/caseHistory";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
export default {
  data() {
    return {
      delDataMsg: {},
      ComputedDrug: {},
      ComputedData: [],
      CID: 0,
      Flag: true,
      CheckDialogVisable: false,
      CDVdrug: {
        cdvname: "",
        cdvnorm: "",
        cdvnum: null,
        cdvuse: "",
        cdvusing: "",
        cdvdid: null,
        cdvstock: null,
        cdvprice: null,
      },
      VIPerI: {
        name: "",
      },
      VIDrug: {
        //这个要实现模糊查询
        dname: "",
      },
      ViCaseHistory: {
        cname: "",
        sex: "",
        age: "",
        weight: "",
        telephone: "",
        address: "",
        chistory: "",
        vtime: "", //就诊时间
        vresult: "", //诊断结果
        vmethod: "", //药方
        idcard: "",
      },
      EditP: {
        cid: 0,
        cname: "",
        sex: "",
        age: "",
        weight: "",
        telephone: "",
        address: "",
        chistory: "",
        vtime: "", //就诊时间
        vresult: "", //诊断结果
        vmethod: "", //药方
        idcard: "",
      },
      ViMethods: [],
      VIDrugLists: [], //查询所有结果
      VIDrugList: [], //选用结果
      VIPerRrcords: [],
      VIPerRrcord: [],
      rules: {
        cname: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        telephone: [
          {
            required: true,
            message: "请输入正确的手机号",
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入详细住址",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
            trigger: "blur",
          },
        ],
        age: [
          {
            required: true,
            message: "请输入年龄",
            pattern: /^\d+$/,
            trigger: "blur",
          },
        ],
        chistory: [
          {
            required: true,
            message: "请确认是否存在过敏及特殊病史",
            trigger: "blur",
          },
        ],
        vresult: [
          {
            required: true,
            message: "请输入诊断结果",
            trigger: "blur",
          },
        ],
        vmethod: [
          {
            required: true,
            message: "请输入处置结果",
            trigger: "blur",
          },
        ],
        // CDVdrug
        cdvnum: [
          {
            required: true,
            message: "请输入数量",
            pattern: /^\d+$/,
            trigger: "blur",
          },
        ],
        cdvuse: [
          {
            required: true,
            message: "请输入数字",
            pattern: /^\d+$/,
            trigger: "blur",
          },
        ],
        cdvname: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        cdvnorm: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        cdvusing: [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //
    // 中间Header的功能
    //
    AddPrescription() {
      // 添加处方、功能即清除目前处方处内容。
      this.$refs["ViCaseHistory"].resetFields();
      this.$refs["VIPerI"].resetFields();
      this.$refs["VIDrug"].resetFields();
    },
    //
    // 右侧患者信息快速查询引用功能
    //
    SearchPerI() {
      queryVIPerRrcord(this.VIPerI.name).then((res) => {
        this.VIPerRrcords = res.data.data;
      });
    },
    Find(rid) {
      for (var i = 0; i < this.VIPerRrcords.length; i++) {
        if (rid == this.VIPerRrcords[i].rid) {
          this.VIPerRrcord = this.VIPerRrcords[i];
          break;
        }
      }
    },
    Selection(rid) {
      this.Find(rid);
      this.ViCaseHistory.cname = this.VIPerRrcord.name;
      this.ViCaseHistory.sex = this.VIPerRrcord.sex;
      this.ViCaseHistory.age = this.VIPerRrcord.age;
      this.ViCaseHistory.idcard = this.VIPerRrcord.idcard;
      this.ViCaseHistory.telephone = this.VIPerRrcord.telephone;
      this.ViCaseHistory.address = this.VIPerRrcord.address;
    },
    //
    // 左侧处方功能
    //
    SearchDrug() {
      queryVIDrug(this.VIDrug.dname).then((res) => {
        this.VIDrugLists = res.data.data;
      });
    },
    CheckFind(did) {
      //根据did找出对应药品信息
      for (var i = 0; i < this.VIDrugLists.length; i++) {
        if (did == this.VIDrugLists[i].did) {
          this.VIDrugList = this.VIDrugLists[i];
          break;
        }
      }
    },
    Check(did) {
      this.CheckFind(did);
      // 给药品信息赋值，进行开方
      this.CDVdrug.cdvname = this.VIDrugList.dname;
      this.CDVdrug.cdvnorm = this.VIDrugList.dnorm;
      this.CDVdrug.cdvdid = this.VIDrugList.did;
      this.CDVdrug.cdvstock = this.VIDrugList.stock;
      this.CDVdrug.cdvprice = this.VIDrugList.dprice;
      // 显示弹窗
      this.CheckDialogVisable = true;
      // 将数组的数据存入数组ViMethods中，进行“处置”结果的生成
      this.ViMethods.push(this.CDVdrug);
    },
    Confirmed() {
      this.$refs.CDVdrug.validate((valid) => {
        if (valid) {
          // 计算使用量，生成余量
          this.ComputedDrug.used = parseInt(this.CDVdrug.cdvnum);
          this.ComputedDrug.dname = this.CDVdrug.cdvname;
          this.ComputedDrug.did = this.CDVdrug.cdvdid;
          this.ComputedDrug.stock = this.CDVdrug.cdvstock;
          this.ComputedDrug.dprice = this.CDVdrug.cdvprice;
          //用staff中转idcard
          this.ComputedDrug.addstaff = this.ViCaseHistory.idcard;
          if (this.ComputedDrug.stock - this.ComputedDrug.used >= 0) {
            this.ViCaseHistory.vmethod +=
              this.ViMethods[0].cdvname +
              "*" +
              this.ViMethods[0].cdvnum +
              "　　" +
              this.ViMethods[0].cdvusing +
              "　用法：" +
              this.ViMethods[0].cdvuse +
              "次/日" +
              "\n";
            this.ComputedData.push(this.ComputedDrug);
            this.ComputedDrug = {};
            this.Closed();
          } else if (this.ComputedDrug.stock - this.ComputedDrug.used < 0) {
            this.$notify({
              title: "失败",
              message: "药品余量不足",
              type: "error",
              duration: 1500,
            });
          }
        }
      });
    },
    //
    // 保存就诊信息并生成病历功能
    //
    SavePrescription() {
      this.$refs.ViCaseHistory.validate((valid) => {
        if (valid) {
          console.log(this.ComputedData);
          // 就诊信息表单数据正确，开始生成病历
          AddCH(this.ViCaseHistory).then((res) => {
            if (res.data.code == 200) {
              // 病历生成成功，计算药品余量
              for (let index = 0; index < this.ComputedData.length; index++) {
                DrugUsingComputed(this.ComputedData[index]).then((res) => {
                  // 药品余量更新成功
                  if (res.data.code == 200) {
                    // 药品使用量计算数组置空
                    return 0;
                  }
                });
              }
              this.ComputedDrug = {};
              this.ComputedData = [];
              this.$notify({
                title: "成功",
                message: "患者：" + this.ViCaseHistory.cname + "的病历已生成",
                type: "success",
                duration: 1500,
              });
              // 默认清除已保存表单的内容
              this.AddPrescription();
            }
          });
        }
      });
    },
    // 临时病历
    temporaryIdCard() {
      this.$prompt("请输入患者身份证号", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        inputErrorMessage: "身份证号格式不正确",
      }).then(({ value }) => {
        this.$notify({
          title: "成功",
          message: "临时病历初步创建",
          type: "success",
          duration: 1500,
        });
        this.AddPrescription();
        this.ViCaseHistory.idcard = value;
      });
    },
    EditPrescription() {
      this.$prompt("请输入患者身份证号", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        inputErrorMessage: "身份证号格式不正确",
      })
        .then(({ value }) => {
          QueryPatientByIdCard(value).then((res) => {
            this.Flag = false;
            this.ViCaseHistory.vmethod = res.data.data[0].vmethod;
            this.ViCaseHistory.cname = res.data.data[0].cname;
            this.ViCaseHistory.sex = res.data.data[0].sex;
            this.ViCaseHistory.age = res.data.data[0].age;
            this.ViCaseHistory.chistory = res.data.data[0].chistory;
            this.ViCaseHistory.telephone = res.data.data[0].telephone;
            this.ViCaseHistory.address = res.data.data[0].address;
            this.ViCaseHistory.weight = res.data.data[0].weight;
            this.ViCaseHistory.vresult = res.data.data[0].vresult;
            this.ViCaseHistory.idcard = res.data.data[0].idcard;
            this.ViCaseHistory.vtime = res.data.data[0].vtime;
            this.CID = res.data.data[0].cid;
            this.delDataMsg.usingTime = res.data.data[0].vtime;
            this.delDataMsg.idcard = res.data.data[0].idcard;
            delData(this.delDataMsg).then((res) => {
              if (res.data.code == 200) {
                return 0;
              }
            });
            // console.log(res.data.data);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    SaveEdit() {
      this.$refs.ViCaseHistory.validate((valid) => {
        if (valid) {
          this.Flag = true;
          this.EditP = this.ViCaseHistory;
          this.EditP.cid = this.CID;
          SaveEditPrescription(this.EditP).then((res) => {
            if (res.data.code == 200) {
              for (let index = 0; index < this.ComputedData.length; index++) {
                DrugUsingComputed(this.ComputedData[index]).then((res) => {
                  // 药品余量更新成功
                  if (res.data.code == 200) {
                    // 药品使用量计算数组置空
                    return 0;
                  }
                });
              }
              this.ComputedDrug = {};
              this.ComputedData = [];
              this.$notify({
                title: "成功",
                message: "处方修改成功，病历已同步更新",
                type: "success",
                duration: 1500,
              });
              this.CID = 0;
              this.AddPrescription();
            }
          });
        }
      });
    },
    Closed() {
      this.$refs["CDVdrug"].resetFields();
      this.CheckDialogVisable = false;
    },
  },
};
</script>

<style>
.ViLabel .el-form-item__label {
  width: 85px !important;
}

#exra .el-form-item__label {
  width: 155px !important;
}
#eltable {
  width: 100% !important;
}
.VICContent h1 {
  font-size: 25px;
  text-align: center;
  padding: 5px;
  margin-top: 10px;
  font-weight: 600;
  font-family: "楷体";
}

.VICContent {
  width: 100%;
  height: 90%;
}

.VICHeader {
  widows: 100%;
  height: 10%;
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  border-bottom: 1px solid black;
}

.VIALL {
  display: flex;
  flex-direction: row;
  width: 100vw;
  height: 77vh;
}

.VIContent {
  width: 59%;
  height: 100%;
  border-bottom: 1px solid black;
  border-top: 1px solid black;
}

.VIRight {
  width: 15%;
  height: 100%;
  border-left: 1px solid black;
}

.VILeft {
  width: 15%;
  height: 100%;
  border-right: 1px solid black;
}

.VIadd {
  width: 100%;
  background-color: white;
  display: flex;
  flex-direction: row-reverse;
}
</style>
